from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import blobstore
import os
import database
import urllib

class People(webapp.RequestHandler):
	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'templates/people.html')
		people = database.Person.all()
		self.response.out.write(template.render(path, {
			'people': people,
		}))

class Person(webapp.RequestHandler):
	def get(self, key):
		person = database.Person.get_by_key_name(urllib.unquote(key))
		if not person: self.error(400); return
		if person.class_name()=='Student':
			path = os.path.join(os.path.dirname(__file__), 'templates/student.html')
		elif person.class_name()=='Professor':
			path = os.path.join(os.path.dirname(__file__), 'templates/professor.html')
		else: self.error(400); return
		iscurrentuser = (users.get_current_user() == person.user)
		self.response.out.write(template.render(path, {
			'person': person,
			'iscurrentuser': iscurrentuser,
		}))

class ChangePicture(webapp.RequestHandler):
	def post(self):
		from google.appengine.api import images
		person = database.Person.all().filter('user =', users.get_current_user()).get()
		if not person: self.error(400); return
		picture = images.Image(self.request.get("picture"))
		picture.resize(width=300, height=300)
		picture.im_feeling_lucky()
		person.picture = db.Blob(picture.execute_transforms(output_encoding=images.JPEG))
		person.put()
		self.redirect('/people/'+person.nick)

application = webapp.WSGIApplication([
		('/people/', People),
		('/people/(.*)', Person),
		('/changepicture', ChangePicture),
	],
	debug=True
)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()


